package com.mmall.seckill.common.redis;

import com.mmall.seckill.util.PropertiesUtil;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by megan on 2018/6/16.
 */
@Component
public class JedisPoolFactory {
    private static JedisPool pool;//jedis连接池

    private static String  ip =PropertiesUtil.getProperty("redis.ip");//连接ip
    private static Integer port= Integer.parseInt(PropertiesUtil.getProperty("redis.port"));//连接端口
    private static String  password= PropertiesUtil.getProperty("redis.password");//连接密码
    private static Integer  timeout= Integer.parseInt(PropertiesUtil.getProperty("redis.timeout"));//超时时间
    private static Integer maxTotal= Integer.parseInt(PropertiesUtil.getProperty("redis.max.total","20")); //最大连接数
    private static Integer maxIdle =Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle","10"));//在jedispool中最大的idle状态(空闲)的jedis实例个数
    private static Integer minIdle =Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle","2"));//在jedispool中最小的idle状态(空闲)的jedis实例个数

    private static Boolean testOnBorrow =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true"));//在borrow一个jedis实例的时候,是否要进行验证操作,如果赋值为 true,则得到的jedis实例是可以用的.
    private static Boolean testOnReturn =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","true"));//在return一个jedis实例的时候,是否要进行验证操作,如果赋值为 true,则放回的jedis实例是可以用的.

    /**
     * 初始化连接
     */
    private static void initPool(){

        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        config.setBlockWhenExhausted(true);//连接耗尽的时候,是否阻塞,false会抛出异常,true阻塞知道超时,默认为true

        pool = new JedisPool(config,ip,port,timeout,password);
    }

    static {
        initPool();
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(Jedis jedis){
        pool.returnResource(jedis);
    }

    public static void returnBrokenResource(Jedis jedis){
        pool.returnBrokenResource(jedis);
    }


    public static void main(String[] args) {
        Jedis jedis =pool.getResource();
        jedis.set("MeganKey","MeganValue");
        returnResource(jedis);

        System.out.printf("jedis end!!");
    }
}
